package com.zzl.springboot_mybatis_demo.rest;

import com.zzl.springboot_mybatis_demo.SpringbootMybatisDemoApplication;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Description：测试RestTemplate工具类
 * Created by 朱正磊 on 2019-08-18 21:31
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootMybatisDemoApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyTestRestTemplate {

    @Resource
    private TestRestTemplate testRestTemplate;

    @LocalServerPort
    private int port;

    private URL base;

    @Resource
    private TestRest testRest;

    @Before
    public void setUp() throws Exception {
        String url = String.format("http://localhost:%d", port);
        System.out.println(String.format("port is : [%d]", port));
        this.base = new URL(url);
        this.testRest.setRestUrl(this.base.toString());
    }

    @Test
    public void testGetInfo() {
        ResponseEntity<String> forEntity = testRestTemplate.getForEntity(this.base.toString() + "/rest/getInfo/{1}", String.class, "李四");
        System.out.println(forEntity.getBody());
    }

    @Test
    public void testGetInfo2() {
        String result = testRest.get("/rest/getInfo/{1}", "zhansgan");
        System.out.println(result);
    }

    @Test
    public void testPostInfo() {
        Map<String, Object> params = new HashMap<>();
        params.put("age", 28);
        String forObject = testRestTemplate.postForObject(this.base.toString() + "/rest/postInfo", params, String.class);
        System.out.println(forObject);
    }

    @Test
    public void testPostInfo2() {
        Map<String, Object> params = new HashMap<>();
        params.put("age", 28);
        HttpEntity entity = new HttpEntity<>(params);
        ResponseEntity<String> exchange = testRestTemplate.exchange(this.base.toString() + "/rest/postInfo", HttpMethod.POST, entity, String.class);
        System.out.println(exchange.getBody());
    }

}
